package com.kuang.pool;

import java.util.concurrent.*;

/**
 * @program: juc
 * @description:
 * @author: 陈恩涛
 * @create: 2021-03-15 10:29
 **/
public class Demo01 {
    public static void main(String[] args) {
        // Executors 工具类，3大方法
        //单个线程
//        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        //创建一个大小固定的线程池
//        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        //可伸缩的
//        ExecutorService threadPool = Executors.newCachedThreadPool();

        System.out.println(Runtime.getRuntime().availableProcessors());

        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                2,
                Runtime.getRuntime().availableProcessors(),
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy());

        try {
            // 最大承载  max + BlockQueue
            // 超过则抛出异常 java.util.concurrent.RejectedExecutionException
            for (int i = 0; i < 8; i++) {
                // 使用了线程池以后，使用线程池来创建线程
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName()+" ok!");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //线程池用完，程序结束，关闭线程池
            threadPool.shutdown();
        }
    }
}
